<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formModel.id ? '编辑分类' : '添加分类'"
    width="500"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="100"
      style="padding-right: 30px"
    >
      <el-form-item label="分类名称" prop="cate_name">
        <el-input
          placeholder="请输入分类名称"
          v-model="formModel.cate_name"
        ></el-input>
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input
          placeholder="请输入分类别名"
          v-model="formModel.cate_alias"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup name="">
import { ref } from 'vue'
import { artAddChannelService, artEditChannelService } from '@/api/article'
const dialogVisible = ref(false)
const formRef = ref()

const formModel = ref({
  id: null,
  cate_name: '',
  cate_alias: ''
})

const rules = {
  cate_name: [
    { required: true, message: '分类名称不能为空', trigger: 'blur' },
    {
      pattern: /^\S{1,10}$/,
      message: '分类名称为1-10个字符',
      trigger: 'blur'
    }
  ],
  cate_alias: [
    { required: true, message: '分类名称不能为空', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '分类名称为1-15个字母或数字',
      trigger: 'blur'
    }
  ]
}

// open({})=〉表单无需渲染，说明是添加
// open({ id， cate_name, ...})=>表单需要渲染，说明是编辑

const open = (row: any) => {
  dialogVisible.value = true
  //拿到数据
  if (row.row) {
    //回显的数据
    formModel.value = row.row
  } else {
    //清空数据
    formModel.value = {
      id: null,
      cate_name: '',
      cate_alias: ''
    }
  }

  //传递了内容，说明是编辑
  // console.log(formModel.value)
}

// 暴露方法
defineExpose({ open })

//通知父组件更新
const emit = defineEmits(['success'])
const onSubmit = async () => {
  await formRef.value.validate()
  const isEdit = formModel.value.id
  // console.log(formModel.value)

  if (isEdit) {
    const res = await artEditChannelService(formModel.value)
    console.log(res)
    ElMessage.success('编辑成功')
  } else {
    const res = await artAddChannelService(formModel.value)
    console.log(res)
    ElMessage.success('添加成功')
  }
  dialogVisible.value = false
  //通知父组件更新
  emit('success', isEdit)
}
</script>
<style scoped></style>
